<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="客户" prop="customerId">
        <el-select v-model="formData.customerId" clearable placeholder="请选择" class="!w-240px">
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="账户名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入账户名称" />
      </el-form-item>
      <el-form-item label="账户编码" prop="no">
        <el-input v-model="formData.no" placeholder="请输入账户编码" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="开启状态" prop="status">
        <el-select v-model="formData.status" clearable placeholder="请选择" class="!w-240px">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="是否默认" prop="defaultStatus">
        <el-select v-model="formData.defaultStatus" clearable placeholder="请选择" class="!w-240px">
          <el-option
            v-for="item in defaultStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { AccountApi, AccountVO } from '@/api/erp/foundation/account'
import { StockApi, DictItemConfigVO } from '@/api/erp/stock/stock'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'

const customerList = ref<CustomerVO[]>([]) // 客户列表

/** ERP 结算账户 表单 */
defineOptions({ name: 'AccountForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const statusOptions = ref<{ value: string; label: string }[]>([])
const defaultStatusOptions = ref<{ value: string; label: string }[]>([])

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  no: undefined,
  remark: undefined,
  status: undefined,
  sort: undefined,
  defaultStatus: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '账户名称不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const queryParams = reactive({
  pageNo: 1,
  pageSize: 100
})
/** 生成基于时间的12位ID */
const generateTimeBasedId = (): number => {
  // 获取当前时间戳（13位）
  const timestamp = new Date().getTime();
  
  // 转换为字符串并取后12位
  const idStr = timestamp.toString().slice(-12);
  
  // 转换为整数返回
  return parseInt(idStr, 10);
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  const statusCode = {
    dictCode: 'status'
  }
  const response = await StockApi.getByDictCode(statusCode)
  statusOptions.value = response.map((item) => ({
    value: item.value,
    label: item.description
  }))
  const defaultStatusCode = {
    dictCode: 'defaultStatus'
  }
  const defaultStatusRes = await StockApi.getByDictCode(defaultStatusCode)
  defaultStatusOptions.value = defaultStatusRes.map((item) => ({
    value: item.value,
    label: item.description
  }))
  customerList.value = (await CustomerApi.getCustomerPage(queryParams)).list
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await AccountApi.getAccount(id)
      formData.value = {
        ...data,
        status: data.status !== null && data.status !== undefined ? String(data.status) : undefined,
        defaultStatus:
          data.defaultStatus !== null && data.defaultStatus !== undefined
            ? String(data.defaultStatus)
            : undefined
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
    if (formType.value === 'create') {
    formData.value.id = generateTimeBasedId();
  }
  try {
    const postData = {
      ...formData.value,
      defaultStatus: formData.value.defaultStatus !== undefined ? Number(formData.value.defaultStatus) : undefined,
      status: formData.value.status !== undefined ? Number(formData.value.status) : undefined
    } as unknown as AccountVO

    if (formType.value === 'create') {
      await AccountApi.createAccount(postData)
      message.success(t('common.createSuccess'))
    } else {
      await AccountApi.updateAccount(postData)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    no: undefined,
    remark: undefined,
    status: undefined,
    sort: undefined,
    defaultStatus: undefined
  }
  formRef.value?.resetFields()
}
</script>